//
//  DetailsViewController.m
//  OurMenu
//
//  Created by lanou3g on 15/10/10.
//  Copyright © 2015年 尹坤. All rights reserved.
//

#import "DetailsViewController.h"
#import "AutoHeight_string.h"
#import "UIImageView+WebCache.h"
#import "DataBaseTool.h"
#import "Steps.h"
#import "MyViewController.h"

static NSString *StepCe = @"stepCell";
static NSString *TopImageCe = @"topImageCell";
static NSString *FeelCe = @"feelCell";
@interface DetailsViewController ()

@end

@implementation DetailsViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //注册cell
    
    [tab registerClass:[StepCell class] forCellReuseIdentifier:StepCe];
    [tab registerClass:[TopImageTableViewCell class] forCellReuseIdentifier:TopImageCe];
    [tab registerClass:[FeelCell class] forCellReuseIdentifier:FeelCe];
    // 分享
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(shareBar)];
    
    //背景图
    backGroundImageView = [[UIImageView alloc] init];
    //设置用户交互 使ImageView上的按钮可以点击
    backGroundImageView.userInteractionEnabled = YES;
    //成品图
    foodImageV = [[UIImageView alloc] init];
    //菜名
    titleLabel = [[UILabel alloc] init];
    //titleLabel.backgroundColor = [UIColor greenColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    //主料标识
    mainLabel = [[UILabel alloc] init];
    mainLabel.text = @"主料:";
    
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(self.view.frame.size.width - 50 , 10, 50, 50);
    //[button setTitle:@"收藏" forState:UIControlStateNormal];
    [backGroundImageView addSubview:button];
    //button.backgroundColor = [UIColor greenColor];
    [button addTarget: self action:@selector(collectMenu:) forControlEvents:UIControlEventTouchUpInside];
    backGroundImageView.userInteractionEnabled = YES;
    
    //主料
    mainMaterilsLabel = [[UILabel alloc] init];
    //mainMaterilsLabel.textAlignment = NSTextAlignmentCenter;
    mainMaterilsLabel.numberOfLines = 0;
    mainMaterilsLabel.font = [UIFont systemFontOfSize:15];
    //mainMaterilsLabel.backgroundColor = [UIColor redColor];
    
    //配料标识
    supportLabel = [[UILabel alloc] init];
    supportLabel.text = @"配料:";
    
    //配料
    supportMaterilsLabel = [[UILabel alloc] init];
    supportMaterilsLabel.numberOfLines = 0;
    [supportMaterilsLabel sizeToFit];
    supportMaterilsLabel.font = [UIFont systemFontOfSize:15];
    //supportMaterilsLabel.backgroundColor = [UIColor redColor];
    
    //烹饪模式按钮
    doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [doneBtn setTitle:@"进入烹饪模式" forState:UIControlStateNormal];
    doneBtn.layer.cornerRadius = 5;
    
    doneBtn.showsTouchWhenHighlighted = YES;
    doneBtn.backgroundColor = [UIColor orangeColor];
    
    //步骤图
    tab = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    tab.delegate = self;
    tab.dataSource = self;
    tab.separatorStyle = UITableViewCellSeparatorStyleNone;
    tab.separatorInset = UIEdgeInsetsMake(10, 10, 10, 5);
    [backGroundImageView addSubview:foodImageV];
    [backGroundImageView addSubview:titleLabel];
    [backGroundImageView addSubview:mainMaterilsLabel];
    [backGroundImageView addSubview:doneBtn];
    [backGroundImageView addSubview:mainLabel];
    [backGroundImageView addSubview:supportLabel];
    [backGroundImageView addSubview:supportMaterilsLabel];
    [self.view addSubview:tab];
    [tab addSubview:backGroundImageView];
    
#pragma mark - 添加菜名、主料、配料、图片
    titleLabel.text = self.dish.title;
    mainMaterilsLabel.text = self.dish.ingredients;
    supportMaterilsLabel.text = self.dish.burden;
    NSString *str = [self.dish.albums lastObject];
    [foodImageV sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"1"]];
    
    //背景图
    backGroundImageView.image = [UIImage imageNamed:@"messages_bg_2@2x"];
    
    [self animateOnEntry];
    
}

- (void)shareBar
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"561df58d67e58e82e1000a51"
                                      shareText:self.dish.title
                                     shareImage:[UIImage imageNamed:@"1.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToQzone,UMShareToQQ, nil]
                                       delegate:self];
    
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url];
}

- (void) animateOnEntry
{
#pragma mark - Frames
    //set initial frames
    //背景图
    backGroundImageView.alpha = 0;
    backGroundImageView.frame = CGRectMake(0, self.yOrigin + MAIN_LABEL_Y_ORIGIN, self.view.frame.size.width, titleLabel.frame.size.height + titleLabel.frame.size.height);
#warning ******  手动修改宽度、高度
    //菜名
    titleLabel.frame = CGRectMake(70, self.yOrigin + MAIN_LABEL_Y_ORIGIN, 120, 50);
    //主料
    mainMaterilsLabel.frame = CGRectMake(70, titleLabel.frame.origin.y + titleLabel.frame.size.height, 280, 120);
    //成品图
    foodImageV.frame = CGRectMake(10, self.yOrigin + IMAGEVIEW_Y_ORIGIN, 50, 50);
    //烹饪模式按钮
    doneBtn.frame = CGRectMake(doneBtn.frame.origin.x, 0-doneBtn.frame.size.height-20, doneBtn.frame.size.width, doneBtn.frame.size.height);
    //步骤图
    tab.alpha = 0;
    tab.frame = CGRectMake(tab.frame.origin.x, tab.frame.size.height + self.view.frame.size.height, tab.frame.size.width, tab.frame.size.height);
    
    //apply animation on ENTERING INTO THE VIEW
    [UIView animateWithDuration:0.3
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^(void)
     {
         
#pragma mark - 位置
         
#warning *******手动修改 x值
         titleLabel.frame = CGRectMake(10, 110, self.view.frame.size.width - 20, 30);
         mainLabel.frame = CGRectMake(40, 140, 50, 40);
         mainMaterilsLabel.frame = CGRectMake(80, 140, mainMaterilsLabel.frame.size.width, 40);
         AutoHeight_string *aut = [[AutoHeight_string alloc] init];
         CGFloat heit = [aut getRowHeight:15 width:[UIScreen mainScreen].bounds.size.width - 100 content:self.dish.burden];
         supportLabel.frame = CGRectMake(40, 180, 50, 40);
         supportMaterilsLabel.frame = CGRectMake(80 , 190, self.view.frame.size.width - 100, heit);
         doneBtn.frame = CGRectMake(backGroundImageView.frame.size.width - 120, 270, 120, 30);
         doneBtn.showsTouchWhenHighlighted = YES;
         [doneBtn addTarget:self action:@selector(cookingModel) forControlEvents:UIControlEventTouchUpInside];
         backGroundImageView.frame = CGRectMake(0, 0, self.view.frame.size.width, 300);
         backGroundImageView.alpha = 1;
         
         tab.frame = CGRectMake(0, 0, tab.frame.size.width, tab.frame.size.height);
         tab.alpha = 1;
         
        // NSLog(@"width %f height %f",foodImageV.frame.size.width,foodImageV.frame.size.height);
         
         foodImageV.frame = CGRectMake(backGroundImageView.center.x - 50, 5, 100, 100);
     }
                     completion:NULL];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#pragma mark - 此处设置cell个数
    return self.dish.steps.count + 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StepCell *cell = [tableView dequeueReusableCellWithIdentifier:StepCe];
    TopImageTableViewCell *topCell = [tableView dequeueReusableCellWithIdentifier:TopImageCe];
    FeelCell *feelCell = [tableView dequeueReusableCellWithIdentifier:FeelCe];
    if (indexPath.row == 0) {
        if (topCell == nil) {
            topCell = [[TopImageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TopImageCe];
        }
        return topCell;
    }else if (indexPath.row == 1){
        if (feelCell == nil) {
            feelCell = [[FeelCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:FeelCe];
        }
        feelCell.selectionStyle = UITableViewCellSelectionStyleNone;
        feelCell.txLabel.font = [UIFont systemFontOfSize:15];
        feelCell.txLabel.text = self.dish.imtro;
        return feelCell;
    }else {
        if (cell == nil) {
            cell = [[StepCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:StepCe];
        }
#pragma mark - 此处添加做菜步骤
        cell.backgroundColor = [UIColor clearColor];
        cell.stepWord.text = [self.dish.steps[indexPath.row - 2] valueForKey:@"step"];
        [cell.stepImage sd_setImageWithURL:[NSURL URLWithString:[self.dish.steps[indexPath.row- 2] valueForKey:@"img"]] placeholderImage:[UIImage imageNamed:@"1"]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 300;
    }else if (indexPath.row == 1){
        AutoHeight_string *autoxxx = [[AutoHeight_string alloc] init];
#pragma mark - 此处许修改感受内容
        CGFloat f =  [autoxxx getRowHeight:15 width:self.view.frame.size.width content:self.dish.imtro];
        return 120 + f - 100;
    }else {
        return 120;
        
    }
}

#pragma mark - 跳转烹饪模式并将所需数据传出

- (void)cookingModel
{
    CookingModelViewController *cooking = [[CookingModelViewController alloc] init];
    cooking.dishs = self.dish;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:cooking];
    nav.navigationBar.translucent = NO;
    nav.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentViewController:nav animated:YES completion:^{
        
    }];
}

//添加收藏
- (void)collectMenu:(UIButton *)buttonn
{
    
    
    DataBaseTool *tool = [[DataBaseTool alloc] init];
    //MyViewController *myview = [[MyViewController alloc] init];
    
    if ([tool isExistsWithName:self.dish.title]) {
        [tool deleteDishes:self.dish.title];
       // [buttonn setTitle:@"收藏" forState:UIControlStateNormal];
        [buttonn setImage:[UIImage imageNamed:@"Button_Favorite"] forState:UIControlStateNormal];
        
    }else{
        DishesMadels *dish = [[DishesMadels alloc] init];
        
        dish.Aalbums = [self.dish.albums lastObject];
       // NSLog(@"%@",[self.dish.albums lastObject]);
        dish.title = self.dish.title;
        dish.tags = self.dish.tags;
        dish.imtro = self.dish.imtro;
        dish.ingredients = self.dish.ingredients;
        dish.burden = self.dish.burden;
        
        [tool insertDishesToTable:dish];
        
        //myview.dish = dish;
        
        //[buttonn setTitle:@"已收藏" forState:UIControlStateNormal];
        [buttonn setImage:[UIImage imageNamed:@"Button_Favorite_Done"] forState:UIControlStateNormal];
        
        alertController = [UIAlertController alertControllerWithTitle:nil message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertController animated:YES completion:nil];
        [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(dismis) userInfo:nil repeats:NO];
        
    }
    
    if ([tool isExistsWithStepsName:self.dish.title]) {
        [tool deleteSteps:self.dish.title];
    }else{
        Steps *steps = [[Steps alloc] init];
        steps.title = self.dish.title;
        for (int i = 0; i < self.dish.steps.count; i++) {
            [steps setValuesForKeysWithDictionary:self.dish.steps[i]];
            [tool insertStepsToTable:steps];
            //myview.steps = steps;
        }
        
    }
    
    
}
- (void)dismis
{
    //[self presentViewController:alertController animated:YES completion:nil];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    DataBaseTool *tool = [[DataBaseTool alloc] init];
    if ([tool isExistsWithName:self.dish.title]) {
        //[button setTitle:@"已收藏" forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"Button_Favorite_Done"] forState:UIControlStateNormal];
    }else{
        //[button setTitle:@"收藏" forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"Button_Favorite"] forState:UIControlStateNormal];
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
